package com.hbu.fleastreet.services.Impl;

import ch.qos.logback.classic.Logger;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hbu.fleastreet.common.Constant;
import com.hbu.fleastreet.dao.IOrderDao;
import com.hbu.fleastreet.entity.Order;
import com.hbu.fleastreet.entity.OrderItem;
import com.hbu.fleastreet.entity.OrderItemDto;
import com.hbu.fleastreet.entity.OrderReview;
import com.hbu.fleastreet.entity.User;
import com.hbu.fleastreet.exception.LoginException;
import com.hbu.fleastreet.exception.OrderException;
import com.hbu.fleastreet.services.ICartService;
import com.hbu.fleastreet.services.IOrderService;
import org.apache.tomcat.util.bcel.Const;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * Created by linmm on 2017/12/25.
 */
@Service("orderService")
public class OrderServiceImpl implements IOrderService {
	private Logger logger = (Logger) LoggerFactory.getLogger(OrderServiceImpl.class);
	@Autowired
	private IOrderDao orderDao;
	@Autowired
	private ICartService cartService;

	@Override
	public OrderItem getOrderItemById(String productId) {
		return orderDao.getOrderItemById(productId);
	}

	@Override
	public List<OrderItem> getAllOrderItem() {
		return orderDao.getAllOrderItem();
	}

	@Override
	public int countAll() {
		return orderDao.countAll();
	}

	@Override
	public PageInfo<Order> findOrderByIndex(Integer pageindex, Integer pageSize) {
		PageInfo<Order> orderPageInfo = null;
		try {
			PageHelper.startPage(pageindex, pageSize);
			List<Order> result = orderDao.findOrderByIndex();
			orderPageInfo = new PageInfo<>(result);
		} catch (Exception e) {
			throw new OrderException(e.getMessage());
		}
		return orderPageInfo;
	}

	@Override
	public List<OrderItem> getItemByOrderId(int orderId) {
		return orderDao.getItemByOrderId(orderId);
	}

	/**
	 * 由于需要同时更新两个表字段，加上事务
	 * @param orderId
	 * @param state
	 */
	@Override
	@Transactional
	public void updateOrderStateAndOrderItemState(int orderId, int state) {
		try {
			orderDao.updateOrderState(orderId, state);
			orderDao.updateOrderItemState(orderId, state);
		} catch (Exception e) {
			throw new OrderException(e.getMessage());
		}
	}

	@Override
	public List<Order> getAllOrders(Integer userId) {
		return orderDao.getAllOrders(userId);
	}

	@Override
	public List<OrderItem> getOrderItemsByOrderId(Integer orderId) {
		return orderDao.getOrderItemsByOrderId(orderId);
	}

	@Override
	@Transactional(isolation = Isolation.DEFAULT)
	public void submitOrder(HttpServletRequest request, HttpServletResponse response, String name, String phone,
			String addr) throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null)
			throw new LoginException("请登录！");
		List<OrderItemDto> orderItemDtos = cartService.listCart(request, true);
		Order order = new Order();
		order.setOrderArea(addr);
		order.setUserPhone(phone);
		order.setConsignee(name);
		order.setUserId(user.getUserId());
		order.setState(Constant.ORDER_STATE_1);
		int orderId = nextVal();
		order.setOrderId(orderId);
		Double total = 0.0d;
		if (order.getTotal() != null) {
			order.getTotal();
		}
		for (OrderItemDto orderItemDto : orderItemDtos) {
			OrderItem orderItem = new OrderItem();
			orderItem.setOrderId(orderId);
			orderItem.setProductQuantity(orderItemDto.getProductQuantity());
			orderItem.setState(Constant.ORDER_STATE_1);
			orderItem.setProductId(orderItemDto.getProductId());
			orderItem.setSubTotal(orderItemDto.getSubTotal());
			orderDao.saveOrderItem(orderItem);
			total = total + orderItemDto.getSubTotal();
			order.setTotal(total);
		}
		order.setTotal(total);
		orderDao.saveOrder(order);
		request.getSession().removeAttribute(Constant.NAME_PREFIX + user.getUserId());

		//重定向到订单列表页面
		//		response.sendRedirect("/fleastreet/order/myorder");
	}

	@Override
	public void insertcomment(Integer orderItemId,String content)throws Exception{
		orderDao.insertcomment(orderItemId, content);
	}

	@Override
	public Integer getOrderStateByOrderId(Integer orderId) throws Exception{
		return orderDao.getOrderStateByOrderId(orderId);
	}

	@Override
	public OrderReview getComment(HttpServletRequest request, HttpServletResponse response, Integer orderItemId)
			throws Exception{
		return orderDao.getCommentbyorderItemId(orderItemId);
	}

	public int nextVal() {
		Integer maxId = orderDao.getMaxId();
		if (maxId == null)
			maxId = Constant.STARTING_VALUE_ORDER;
		return maxId + 1;
	}

}
